package controllers

import (
	"fmt"
	models "gotest/models"
	pager "gotest/pager"
	"strconv"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

var (
	sSql string
	err  error
)

type MainController struct {
	beego.Controller
}

func (c *MainController) Get() {
	if c.GetSession("UserName") != nil {
		c.Data["IsAdmin"] = true
	}
	c.Layout = "basic-layout.tpl"
	c.LayoutSections = make(map[string]string)
	c.LayoutSections["Header"] = "header.tpl"
	c.LayoutSections["Footer"] = "footer.tpl"
	var users []models.User
	o := orm.NewOrm()
	o.Using("default") // 默认使用 default，你可以指定为其他数据库
	sSql = "select id,name,hours from user"
	_, err := o.Raw(sSql).QueryRows(&users)
	if err != nil {
		fmt.Println("读取数据库出错")
	}
	c.Data["Users"] = users
	c.Data["Website"] = "beego.me"
	c.Data["Email"] = "astaxie@gmail.com"
	c.TplName = "index.tpl"
}

func (main *MainController) InserUser() {
	user := models.User{}
	if err := main.ParseForm(&user); err != nil {
		beego.Error("无法解析. 原因: ", err)
	} else {
		flash := beego.NewFlash()
		o := orm.NewOrm()
		o.Using("default")
		beego.Info(user.Name, user.Hours)
		err = o.Begin()
		_, err := o.Insert(&user)
		if err != nil {
			o.Rollback()
			beego.Error(err)
		} else {
			o.Commit()
			msg := fmt.Sprintf("用户创建成功")
			beego.Debug(msg)
			flash.Notice(msg)
			flash.Store(&main.Controller)
		}
		main.Ctx.Redirect(302, "/")
	}
}

func (main *MainController) Delete() {
	main.Layout = "basic-layout.tpl"
	main.LayoutSections = make(map[string]string)
	main.LayoutSections["Header"] = "header.tpl"
	main.LayoutSections["Footer"] = "footer.tpl"
	main.TplName = "index.tpl"
	userid, _ := strconv.Atoi(main.Ctx.Input.Param(":id"))
	beego.Info("UserId为:", userid)
	o := orm.NewOrm()
	o.Using("default")
	if exist := o.QueryTable("User").Filter("Id", userid).Exist(); exist {
		if num, err := o.Delete(&models.User{Id: userid}); err == nil {
			beego.Info("删除成功", num)
		} else {
			beego.Error("删除失败: ", err)
		}
	} else {
		beego.Info("用户不存在.")
	}
	main.Ctx.Redirect(302, "/")
}

func (main *MainController) Add() {
	main.Layout = "basic-layout.tpl"
	main.LayoutSections = make(map[string]string)
	main.LayoutSections["Header"] = "header.tpl"
	main.LayoutSections["Footer"] = "footer.tpl"
	main.TplName = "add.tpl"
}

func (main *MainController) Edit() {
	user := models.User{}
	userid, _ := strconv.Atoi(main.Ctx.Input.Param(":id"))
	o := orm.NewOrm()
	o.Using("default")
	o.QueryTable("User").Filter("Id", userid).One(&user)
	main.Data["User"] = user
	main.Layout = "basic-layout.tpl"
	main.LayoutSections = make(map[string]string)
	main.LayoutSections["Header"] = "header.tpl"
	main.LayoutSections["Footer"] = "footer.tpl"
	main.TplName = "edit.tpl"
}

func (main *MainController) UpdateUser() {
	user := models.User{}
	if err := main.ParseForm(&user); err != nil {
		beego.Error("无法解析. 原因: ", err)
	} else {
		flash := beego.NewFlash()
		o := orm.NewOrm()
		o.Using("default")
		beego.Info(user.Name, user.Hours)
		err = o.Begin()
		_, err := o.Update(&user)
		if err != nil {
			o.Rollback()
			beego.Error(err)
		} else {
			o.Commit()
			msg := fmt.Sprintf("用户修改成功")
			beego.Debug(msg)
			flash.Notice(msg)
			flash.Store(&main.Controller)
		}
		main.Ctx.Redirect(302, "/")
	}
}

func (main *MainController) Login() {
	main.TplName = "login.tpl"
	if main.Ctx.Input.Method() == "POST" {
		inputs := main.Input()
		userName := inputs.Get("username")
		pwd := inputs.Get("pwd")
		if userName == "admin" && pwd == "6906606" {
			main.SetSession("UserName", userName)
			beego.Info("session:", main.GetSession("UserName"))
			main.Ctx.Redirect(302, "/")
		} else {
			main.TplName = "error.tpl"
		}

	}
}

func (main *MainController) LogOut() {
	main.DelSession("UserName")
	main.TplName = "login.tpl"
}

func (main *MainController) List() {
	main.Layout = "basic-layout.tpl"
	main.LayoutSections = make(map[string]string)
	main.LayoutSections["Header"] = "header.tpl"
	main.LayoutSections["Footer"] = "footer.tpl"
	var page int
	var errd error
	var num int
	var pagesize int = 10 //每页多少条数据
	var pageBegin int
	page, errd = main.GetInt("page") //获取页数
	if errd != nil && page < 1 {
		page = 1
	}
	pageBegin = (page - 1) * pagesize
	var users []models.User
	o := orm.NewOrm()
	o.Using("default") // 默认使用 default，你可以指定为其他数据库
	sSql = "select id,name,hours from user limit " + strconv.Itoa(pageBegin) + "," + strconv.Itoa(pagesize)
	_, err := o.Raw(sSql).QueryRows(&users)
	if err != nil {
		fmt.Println("读取数据库出错")
	}
	sSql = "select count(id) from user"
	o.Raw(sSql).QueryRow(&num)
	var pages pager.Page = pager.NewPage(page, pagesize, num, "/List")
	main.Data["page"] = pages.Show()
	main.Data["Users"] = users
	main.TplName = "list.tpl"
}
